<template>
  <div class="component-center">
    <!-- 页面标题 -->
    <div class="page-header">
      <h1>组件中心</h1>
      <p>丰富的UI组件库，提升开发效率</p>
    </div>

    <!-- 组件分类导航 -->
    <div class="category-nav">
      <el-tabs v-model="activeCategory" @tab-click="handleCategoryChange">
        <el-tab-pane
          v-for="category in categories"
          :key="category.name"
          :label="category.label"
          :name="category.name"
        >
          <!-- 搜索栏 -->
          <div class="search-section mb-4">
            <el-input
              v-model="searchText"
              placeholder="搜索组件..."
              size="large"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- 组件网格 -->
          <el-row :gutter="24">
            <el-col
              :span="8"
              v-for="component in filteredComponents"
              :key="component.id"
              class="mb-4"
            >
              <el-card class="component-card" shadow="hover">
                <div class="component-header">
                  <div class="component-icon" :style="{background: component.color}">
                    <el-icon :size="24">
                      <component :is="component.icon"/>
                    </el-icon>
                  </div>
                  <div class="component-title">
                    <h3>{{ component.name }}</h3>
                    <p>{{ component.description }}</p>
                  </div>
                </div>

                <div class="component-preview">
                  <div class="preview-demo">
                    <div v-if="component.category === 'basic'" class="demo-buttons">
                      <button class="demo-btn primary">主要按钮</button>
                      <button class="demo-btn success">成功按钮</button>
                    </div>
                    <div v-else-if="component.category === 'data'" class="demo-data">
                      <div v-if="component.name === 'DataTable'" class="demo-table">
                        <div class="table-header">姓名 | 年龄 | 部门</div>
                        <div class="table-row">张三 | 25 | 开发部</div>
                      </div>
                      <div v-else class="demo-chart">
                        <div class="chart-bar bar1"></div>
                        <div class="chart-bar bar2"></div>
                        <div class="chart-bar bar3"></div>
                      </div>
                    </div>
                    <div v-else class="demo-placeholder">
                      <el-icon :size="32"><component :is="component.icon"/></el-icon>
                    </div>
                  </div>
                </div>

                <div class="component-meta">
                  <el-tag size="small" :type="component.complexity">
                    {{ getComplexityText(component.complexity) }}
                  </el-tag>
                  <el-tag size="small" effect="plain">{{ component.version }}</el-tag>
                  <div class="component-stats">
                    <span>
                      <el-icon><Download /></el-icon>
                      {{ component.usage }}
                    </span>
                  </div>
                </div>

                <div class="component-actions">
                  <el-button size="small" @click="viewCode(component)">
                    <el-icon><View /></el-icon>
                    查看代码
                  </el-button>
                  <el-button size="small" type="primary" @click="useComponent(component)">
                    <el-icon><Plus /></el-icon>
                    使用组件
                  </el-button>
                </div>
              </el-card>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
    </div>

    <!-- 代码预览弹窗 -->
    <el-dialog
      v-model="codeVisible"
      :title="selectedComponent ? `${selectedComponent.name} - 代码示例` : ''"
      width="70%"
      top="5vh"
    >
      <el-tabs v-model="codeTab">
        <el-tab-pane label="模板代码" name="template">
          <pre><code>{{ selectedComponent?.code?.template }}</code></pre>
        </el-tab-pane>
        <el-tab-pane label="脚本代码" name="script">
          <pre><code>{{ selectedComponent?.code?.script }}</code></pre>
        </el-tab-pane>
        <el-tab-pane label="样式代码" name="style">
          <pre><code>{{ selectedComponent?.code?.style }}</code></pre>
        </el-tab-pane>
      </el-tabs>
      <template #footer>
        <el-button @click="codeVisible = false">关闭</el-button>
        <el-button type="primary" @click="copyCode">复制代码</el-button>
      </template>
    </el-dialog>

    <!-- 使用指南弹窗 -->
    <el-dialog
      v-model="guideVisible"
      :title="selectedComponent ? `${selectedComponent.name} - 使用指南` : ''"
      width="60%"
    >
      <div class="usage-guide">
        <h3>组件描述</h3>
        <p>{{ selectedComponent?.fullDescription }}</p>
        
        <h3>主要特性</h3>
        <ul>
          <li v-for="feature in selectedComponent?.features" :key="feature">
            {{ feature }}
          </li>
        </ul>
        
        <h3>使用步骤</h3>
        <ol>
          <li v-for="step in selectedComponent?.steps" :key="step">
            {{ step }}
          </li>
        </ol>
        
        <h3>API 参数</h3>
        <el-table :data="selectedComponent?.props" size="small">
          <el-table-column prop="name" label="参数名" width="120"/>
          <el-table-column prop="type" label="类型" width="100"/>
          <el-table-column prop="default" label="默认值" width="100"/>
          <el-table-column prop="description" label="说明"/>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="guideVisible = false">关闭</el-button>
        <el-button type="primary" @click="viewCode(selectedComponent)">查看代码</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import {
  Search,
  View,
  Download,
  Plus,
  Grid,
  Document,
  TrendCharts,
  User,
  Bell,
  Setting
} from '@element-plus/icons-vue'

// 响应式数据
const activeCategory = ref('basic')
const searchText = ref('')
const codeVisible = ref(false)
const guideVisible = ref(false)
const selectedComponent = ref(null)
const codeTab = ref('template')

// 组件分类
const categories = ref([
  { name: 'basic', label: '基础组件' },
  { name: 'form', label: '表单组件' },
  { name: 'data', label: '数据展示' },
  { name: 'navigation', label: '导航组件' },
  { name: 'feedback', label: '反馈组件' },
  { name: 'others', label: '其他组件' }
])

// 组件数据
const components = ref([
  {
    id: 1,
    name: 'CustomButton',
    description: '自定义按钮组件，支持多种样式和状态',
    fullDescription: '基于 Element Plus 的 Button 组件封装，提供了更多的自定义样式和交互效果。支持渐变背景、动画效果、图标组合等特性。',
    category: 'basic',
    icon: 'Grid',
    color: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
    complexity: 'success',
    version: 'v1.2.0',
    usage: 245,
    features: ['多种预设样式', '支持图标', '加载状态', '禁用状态', '自定义尺寸'],
    steps: [
      '导入 CustomButton 组件',
      '在模板中使用 <CustomButton>',
      '通过 props 配置样式和行为',
      '监听点击事件进行交互'
    ],
    props: [
      { name: 'type', type: 'String', default: 'primary', description: '按钮类型' },
      { name: 'size', type: 'String', default: 'medium', description: '按钮尺寸' },
      { name: 'loading', type: 'Boolean', default: 'false', description: '加载状态' },
      { name: 'disabled', type: 'Boolean', default: 'false', description: '禁用状态' }
    ],
    code: {
      template: `<template>
  <el-button
    :type="type"
    :size="size"
    :loading="loading"
    :disabled="disabled"
    :class="customClass"
    @click="handleClick"
  >
    <el-icon v-if="icon && !loading">
      <component :is="icon"/>
    </el-icon>
    <slot></slot>
  </el-button>
</template>`,
      script: `<script setup>
import { computed } from 'vue'

const props = defineProps({
  type: { type: String, default: 'primary' },
  size: { type: String, default: 'medium' },
  loading: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  icon: String
})

const emit = defineEmits(['click'])

const customClass = computed(() => {
  return {
    'custom-button': true,
    [\`custom-button--\${props.type}\`]: true,
    [\`custom-button--\${props.size}\`]: true
  }
})

const handleClick = (event) => {
  if (!props.disabled && !props.loading) {
    emit('click', event)
  }
}
<\/script>`,
      style: `.custom-button {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.custom-button--primary {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  border: none;
  color: white;
}

.custom-button:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}`
    }
  },
  {
    id: 2,
    name: 'DataTable',
    description: '增强型数据表格，支持排序、筛选、分页等功能',
    fullDescription: '基于 Element Plus Table 组件的增强版本，提供了更丰富的数据操作功能和更好的用户体验。',
    category: 'data',
    icon: 'Document',
    color: 'linear-gradient(135deg, #f093fb 0%, #f5576c 100%)',
    complexity: 'warning',
    version: 'v2.1.0',
    usage: 189,
    features: ['高性能虚拟滚动', '多列排序', '高级筛选', '导出功能', '自定义列'],
    steps: [
      '准备表格数据结构',
      '配置列定义',
      '设置分页参数',
      '添加操作按钮',
      '处理数据变更事件'
    ],
    props: [
      { name: 'data', type: 'Array', default: '[]', description: '表格数据' },
      { name: 'columns', type: 'Array', default: '[]', description: '列配置' },
      { name: 'loading', type: 'Boolean', default: 'false', description: '加载状态' },
      { name: 'pagination', type: 'Object', default: '{}', description: '分页配置' }
    ],
    code: {
      template: `<template>
  <div class="data-table">
    <el-table
      :data="tableData"
      :loading="loading"
      @sort-change="handleSort"
      @selection-change="handleSelection"
    >
      <el-table-column
        v-for="column in columns"
        :key="column.prop"
        :prop="column.prop"
        :label="column.label"
        :sortable="column.sortable"
        :width="column.width"
      >
        <template #default="{ row }" v-if="column.render">
          <component :is="column.render" :row="row"/>
        </template>
      </el-table-column>
    </el-table>
    
    <el-pagination
      v-if="showPagination"
      :current-page="pagination.page"
      :page-size="pagination.size"
      :total="pagination.total"
      @current-change="handlePageChange"
    />
  </div>
</template>`,
      script: `<script setup>
const props = defineProps({
  data: { type: Array, default: () => [] },
  columns: { type: Array, default: () => [] },
  loading: { type: Boolean, default: false },
  pagination: { type: Object, default: () => ({}) }
})

const emit = defineEmits(['sort-change', 'page-change', 'selection-change'])

const showPagination = computed(() => {
  return Object.keys(props.pagination).length > 0
})

const handleSort = (sortInfo) => {
  emit('sort-change', sortInfo)
}

const handlePageChange = (page) => {
  emit('page-change', page)
}

const handleSelection = (selection) => {
  emit('selection-change', selection)
}
<\/script>`,
      style: `.data-table {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.el-table {
  border-radius: 4px;
}

.el-pagination {
  margin-top: 16px;
  text-align: right;
}`
    }
  },
  {
    id: 3,
    name: 'ChartWidget',
    description: '图表组件，支持多种图表类型和实时数据',
    fullDescription: '集成了 ECharts 的图表组件，支持柱状图、折线图、饼图等多种类型，提供了丰富的配置选项和实时数据更新功能。',
    category: 'data',
    icon: 'TrendCharts',
    color: 'linear-gradient(135deg, #4facfe 0%, #00f2fe 100%)',
    complexity: 'danger',
    version: 'v1.5.0',
    usage: 167,
    features: ['多图表类型', '实时数据', '响应式设计', '主题定制', '导出图片'],
    steps: [
      '安装 ECharts 依赖',
      '配置图表数据',
      '选择图表类型',
      '设置图表选项',
      '监听数据变化'
    ],
    props: [
      { name: 'type', type: 'String', default: 'line', description: '图表类型' },
      { name: 'data', type: 'Object', default: '{}', description: '图表数据' },
      { name: 'options', type: 'Object', default: '{}', description: '图表选项' },
      { name: 'theme', type: 'String', default: 'default', description: '图表主题' }
    ],
    code: {
      template: `<template>
  <div class="chart-widget">
    <div
      ref="chartRef"
      :style="{ width: width, height: height }"
      class="chart-container"
    ></div>
  </div>
</template>`,
      script: `<script setup>
import { ref, onMounted, watch } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  type: { type: String, default: 'line' },
  data: { type: Object, required: true },
  options: { type: Object, default: () => ({}) },
  width: { type: String, default: '100%' },
  height: { type: String, default: '300px' }
})

const chartRef = ref(null)
let chartInstance = null

const initChart = () => {
  if (chartRef.value) {
    chartInstance = echarts.init(chartRef.value)
    updateChart()
  }
}

const updateChart = () => {
  if (chartInstance) {
    const option = {
      ...getDefaultOption(),
      ...props.options,
      series: [{
        type: props.type,
        data: props.data
      }]
    }
    chartInstance.setOption(option)
  }
}

watch(() => props.data, updateChart, { deep: true })

onMounted(() => {
  initChart()
})
<\/script>`,
      style: `.chart-widget {
  background: white;
  border-radius: 8px;
  padding: 16px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.chart-container {
  width: 100%;
  height: 100%;
}`
    }
  },
  {
    id: 4,
    name: 'NotificationBell',
    description: '消息通知组件，支持实时消息提醒',
    fullDescription: '用于显示系统消息和通知的组件，支持不同类型的消息展示、消息数量提示和实时更新功能。',
    category: 'feedback',
    icon: 'Bell',
    color: 'linear-gradient(135deg, #43e97b 0%, #38f9d7 100%)',
    complexity: 'warning',
    version: 'v1.3.0',
    usage: 134,
    features: ['实时消息提醒', '消息分类', '未读数量显示', '历史消息查看', '消息操作'],
    steps: [
      '导入通知组件',
      '配置消息数据源',
      '设置消息类型',
      '处理消息点击事件',
      '实现消息状态管理'
    ],
    props: [
      { name: 'messages', type: 'Array', default: '[]', description: '消息列表' },
      { name: 'showBadge', type: 'Boolean', default: 'true', description: '显示数量徽章' },
      { name: 'maxCount', type: 'Number', default: '99', description: '最大显示数量' },
      { name: 'placement', type: 'String', default: 'bottom', description: '弹出位置' }
    ],
    code: {
      template: `<template>
  <el-badge :value="unreadCount" :hidden="!showBadge || unreadCount === 0">
    <el-popover placement="bottom" width="300" trigger="click">
      <template #reference>
        <el-button circle>
          <el-icon><Bell /></el-icon>
        </el-button>
      </template>
      <div class="notification-panel">
        <div class="notification-header">
          <span>消息通知</span>
          <el-button text @click="markAllAsRead">全部已读</el-button>
        </div>
        <div class="notification-list">
          <div
            v-for="message in messages"
            :key="message.id"
            class="notification-item"
            :class="{ unread: !message.read }"
            @click="handleMessageClick(message)"
          >
            <div class="message-content">
              <div class="message-title">{{ message.title }}</div>
              <div class="message-text">{{ message.content }}</div>
              <div class="message-time">{{ formatTime(message.time) }}</div>
            </div>
          </div>
        </div>
      </div>
    </el-popover>
  </el-badge>
</template>`,
      script: `<script setup>
import { computed } from 'vue'
import { Bell } from '@element-plus/icons-vue'

const props = defineProps({
  messages: { type: Array, default: () => [] },
  showBadge: { type: Boolean, default: true },
  maxCount: { type: Number, default: 99 }
})

const emit = defineEmits(['message-click', 'mark-read'])

const unreadCount = computed(() => {
  const count = props.messages.filter(msg => !msg.read).length
  return count > props.maxCount ? \`\${props.maxCount}+\` : count
})

const handleMessageClick = (message) => {
  emit('message-click', message)
  if (!message.read) {
    emit('mark-read', message.id)
  }
}

const markAllAsRead = () => {
  props.messages.forEach(msg => {
    if (!msg.read) {
      emit('mark-read', msg.id)
    }
  })
}
<\/script>`,
      style: `.notification-panel {
  .notification-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 12px 0;
    border-bottom: 1px solid #ebeef5;
  }

  .notification-list {
    max-height: 300px;
    overflow-y: auto;
  }

  .notification-item {
    padding: 12px;
    border-bottom: 1px solid #f0f2f5;
    cursor: pointer;
    
    &.unread {
      background: #f0f9ff;
      border-left: 3px solid #409eff;
    }
    
    &:hover {
      background: #f5f7fa;
    }
  }
}`
    }
  }
])

// 计算属性
const filteredComponents = computed(() => {
  let result = components.value.filter(comp => comp.category === activeCategory.value)

  if (searchText.value) {
    result = result.filter(comp =>
      comp.name.toLowerCase().includes(searchText.value.toLowerCase()) ||
      comp.description.toLowerCase().includes(searchText.value.toLowerCase())
    )
  }

  return result
})

// 方法
const handleCategoryChange = () => {
  searchText.value = ''
}

const handleSearch = () => {
  // 搜索逻辑已在计算属性中处理
}

const getComplexityText = (complexity) => {
  const texts = {
    'success': '简单',
    'warning': '中等',
    'danger': '复杂'
  }
  return texts[complexity] || '未知'
}

const viewCode = (component) => {
  selectedComponent.value = component
  codeVisible.value = true
  codeTab.value = 'template'
}

const useComponent = (component) => {
  selectedComponent.value = component
  guideVisible.value = true
}

const copyCode = () => {
  const code = selectedComponent.value?.code?.[codeTab.value] || ''
  navigator.clipboard.writeText(code).then(() => {
    ElMessage.success('代码已复制到剪贴板')
  }).catch(() => {
    ElMessage.error('复制失败，请手动复制')
  })
}
</script>

<style scoped lang="scss">
.component-center {
  padding: 20px;
  background: linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%);
  min-height: calc(100vh - 120px);

  .page-header {
    margin-bottom: 32px;
    
    h1 {
      font-size: 28px;
      font-weight: 600;
      color: #2c3e50;
      margin: 0 0 8px 0;
    }
    
    p {
      color: #7f8c8d;
      font-size: 14px;
      margin: 0;
    }
  }

  .category-nav {
    :deep(.el-tabs__header) {
      background: white;
      border-radius: 8px;
      padding: 8px;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      margin-bottom: 24px;
    }
  }

  .search-section {
    :deep(.el-input__inner) {
      border-radius: 8px;
    }
  }

  .component-card {
    border-radius: 16px;
    border: none;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    
    &:hover {
      transform: translateY(-4px);
      box-shadow: 0 8px 30px rgba(0, 0, 0, 0.15);
    }
    
    :deep(.el-card__body) {
      padding: 24px;
    }
    
    .component-header {
      display: flex;
      align-items: flex-start;
      margin-bottom: 20px;
      
      .component-icon {
        width: 48px;
        height: 48px;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-right: 16px;
        color: white;
        flex-shrink: 0;
      }
      
      .component-title {
        flex: 1;
        
        h3 {
          font-size: 18px;
          font-weight: 600;
          color: #2c3e50;
          margin: 0 0 8px 0;
        }
        
        p {
          font-size: 14px;
          color: #7f8c8d;
          line-height: 1.5;
          margin: 0;
        }
      }
    }
    
    .component-preview {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      margin-bottom: 16px;
      min-height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      
      .preview-demo {
        width: 100%;
        
        .demo-buttons {
          display: flex;
          gap: 8px;
          
          .demo-btn {
            padding: 8px 16px;
            border-radius: 6px;
            border: none;
            cursor: pointer;
            font-size: 14px;
            
            &.primary {
              background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
              color: white;
            }
            
            &.success {
              background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
              color: white;
            }
          }
        }
        
        .demo-data {
          .demo-table {
            font-size: 12px;
            width: 100%;
            
            .table-header {
              background: #e9ecef;
              padding: 8px;
              font-weight: 600;
              border-radius: 4px 4px 0 0;
            }
            
            .table-row {
              background: white;
              padding: 8px;
              border: 1px solid #e9ecef;
              border-top: none;
              border-radius: 0 0 4px 4px;
            }
          }
          
          .demo-chart {
            display: flex;
            align-items: end;
            gap: 8px;
            height: 40px;
            justify-content: center;
            
            .chart-bar {
              width: 20px;
              background: linear-gradient(to top, #4facfe 0%, #00f2fe 100%);
              border-radius: 2px 2px 0 0;
              
              &.bar1 { height: 60%; }
              &.bar2 { height: 100%; }
              &.bar3 { height: 40%; }
            }
          }
        }
        
        .demo-placeholder {
          display: flex;
          align-items: center;
          justify-content: center;
          color: #7f8c8d;
        }
      }
    }
    
    .component-meta {
      display: flex;
      align-items: center;
      gap: 8px;
      margin-bottom: 16px;
      
      .component-stats {
        margin-left: auto;
        display: flex;
        align-items: center;
        gap: 4px;
        font-size: 12px;
        color: #7f8c8d;
      }
    }
    
    .component-actions {
      display: flex;
      gap: 8px;
    }
  }

  .mb-4 {
    margin-bottom: 24px;
  }

  // 代码预览样式
  :deep(.el-dialog__body) {
    pre {
      background: #f8f9fa;
      border-radius: 8px;
      padding: 16px;
      overflow-x: auto;
      
      code {
        font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
        font-size: 14px;
        line-height: 1.5;
      }
    }
  }

  .usage-guide {
    h3 {
      font-size: 18px;
      font-weight: 600;
      color: #2c3e50;
      margin: 24px 0 12px 0;
      
      &:first-child {
        margin-top: 0;
      }
    }
    
    p {
      color: #606266;
      line-height: 1.6;
      margin-bottom: 16px;
    }
    
    ul, ol {
      color: #606266;
      line-height: 1.6;
      padding-left: 20px;
      
      li {
        margin-bottom: 8px;
      }
    }
  }
}
</style>
